package com.kaisa.activity.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.kaisa.activity.BaseApp;
import com.kaisa.activity.R;
import com.kaisa.activity.bean.SearchHistoryDb;
import com.kaisa.activity.bean.SortSearchBean;
import com.kaisa.activity.ui.SearchCountriesActivity;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

/**
 * Created by Administrator on 2015/12/13.
 * sortActivity-gridview 适配器
 */
public class SortSearchAdapter extends AppBaseAdapter<SortSearchBean.HotTermsEntity>{
    final DbManager db;
    public SortSearchAdapter(List<SortSearchBean.HotTermsEntity> list, Context context) {
        super(list, context);
        inflater = LayoutInflater.from(context);
        db = BaseApp.getDB();
    }


    @Override
    public View getItemView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.item_grid_sortactivity,parent,false);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        x.view().inject(this,convertView);
        //映射数据
        holder.searchButton.setText(list.get(position).getHotTerm());

        //点击跳转
        holder.searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String queryKey = list.get(position).getHotTerm();
                Intent intent = new Intent(context, SearchCountriesActivity.class);
                intent.putExtra("queryKey", queryKey);
                context.startActivity(intent);

                SearchHistoryDb historyDb = new SearchHistoryDb(queryKey);

                try {
                   // DbManager db = BaseApp.getDB();
                   // db.dropTable(SearchHistoryDb.class);
                    db.save(historyDb);
                    
                } catch (DbException e) {
                    e.printStackTrace();
                }

            }
        });
        return convertView;
    }

    public static class ViewHolder extends BaseViewHolder{
        @ViewInject(R.id.btn_sortactvity_search)
        private Button searchButton;


        public ViewHolder(View convertView) {
            super(convertView);
            x.view().inject(this,convertView);
        }
    }
}
